import { modalCondition } from './config/modalConfig';
import services from './service';
import _ from 'lodash';
import { Model, ItemUtils, unitsPrice } from '@/utils'
import { tableFields } from './config/tableFields'
import { base } from '@/config';
import pageConfig from './config/pageConfig';
const {namespace,listenRouter} = pageConfig
const initState = {
  fields: tableFields, // 列表-表格
  pagination: { // 分页
    ...base.initPage,
  },
  list: [], // 列表-数据
  modalCondition: modalCondition,
  upperAreaList:[] //上级区域下拉列表
}

export default Model.extend({
  namespace: namespace,
  state: _.cloneDeep(initState),
  subscriptions: {
    setup({ dispatch, listen }: any) {
      listen(listenRouter, () => {
        dispatch({
          type: 'updateState',
          payload: {
            ..._.cloneDeep(initState),
          }
        })

        dispatch({ type: 'fetchList' });
      });
    }
  },
  effects: {
    //新增区域
    * fetchRegionAdd({ payload }: any, { callWithConfirmLoading, select, update, put }: any) {
      yield callWithConfirmLoading(services.fetchRegionAdd, { ...payload }, { successMsg: '新增区域成功' });
      yield put({ type: 'fetchList', payload: { pn: 1, ps: 10, } })
    },
    //上级区域下拉列表
    * fetchUpperAreaList({ payload }: any, { callWithSpinning, put, update }: any) {
      const data = yield callWithSpinning(services.fetchRegionList, { pn: 1, ps: 9999 });
      if (data) {

        const { datas } = data;
        const upperAreaList = datas.length > 0 ? datas.map((item: any, index: number) => {
          return {
            label: item.name,
            value: item.id
          }
        }) : []

        yield update({
          upperAreaList
        })
        yield put({ type: 'updateModalCondition' })
      }
    },
    // 搜索列表
    * fetchList({ payload }: any, { callWithSpinning, select, update }: any) {
      const {
        pagination: { ps, pn },
        filterParams,
        countStatus,
      } = yield select((_: any) => _[namespace]);

      const searchParams = {
        ps,
        pn,
        status: countStatus, // 统计状态
        ...filterParams,
        ...payload,
      }

      const data = yield callWithSpinning(services.fetchRegionList, searchParams);

      if (data) {
        const { datas, pn, ps, tc } = data;
        yield update({
          list: datas,
          pagination: {
            ps,
            pn,
            total: tc,
            current: pn, // 组件需要
            pageSize: ps, // 组件需要
          },
        });
      }
    },
  },
  reducers: {
    updateModalCondition(state: any, { payload }: any) {
      const { upperAreaList } = state

      const _modalCondition = ItemUtils.getItemType(_.cloneDeep(modalCondition))
        .extend([
          {
            title: 'pid',
            selectCondition: upperAreaList
          }
        ]).values()

      return {
        ...state,
        modalCondition: _modalCondition
      }
    }
  }
})
